/*
 * TextAreaDialog.java - A dialog box with a text area
 */

package org.lex.swing.widgets;

import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

public class TextAreaDialog extends EnhancedDialog {
	public TextAreaDialog(Window parent, String title, String msg, Throwable t) {
		this(parent, title, msg, UIManager.getIcon("OptionPane.errorIcon"), throwableToString(t));
	}

	public TextAreaDialog(Window parent, String title, String caption, Icon icon, String text) {
		super(parent, title, true);
		initialize(caption, icon, text);
	}

	public void ok() {
		dispose();
	}

	public void cancel() {
		dispose();
	}

	private void initialize(String caption, Icon icon, String text) {
		JPanel content = new JPanel(new BorderLayout(12, 12));
		content.setBorder(new EmptyBorder(12, 12, 12, 12));
		setContentPane(content);

		Box iconBox = new Box(BoxLayout.Y_AXIS);
		iconBox.add(new JLabel(icon));
		iconBox.add(Box.createGlue());
		content.add(BorderLayout.WEST, iconBox);

		JPanel centerPanel = new JPanel(new BorderLayout(6, 6));

		centerPanel.add(BorderLayout.NORTH, new JLabel(caption));

		JTextArea textArea = new JTextArea(10, 80);

		textArea.setText(text);
		textArea.setLineWrap(true);
		textArea.setCaretPosition(0);
		centerPanel.add(BorderLayout.CENTER, new JScrollPane(textArea));

		content.add(BorderLayout.CENTER, centerPanel);

		Box buttons = new Box(BoxLayout.X_AXIS);
		buttons.add(Box.createGlue());
		JButton ok = new JButton("OK");
		ok.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				dispose();
			}
		});
		buttons.add(ok);
		buttons.add(Box.createGlue());
		content.add(BorderLayout.SOUTH, buttons);

		getRootPane().setDefaultButton(ok);

		pack();
		setLocationRelativeTo(getParent());
		setVisible(true);
	}

	/**
	 * Returns a string containing the stack trace of the given throwable.
	 */
	private static String throwableToString(Throwable t) {
		StringWriter s = new StringWriter();
		t.printStackTrace(new PrintWriter(s));
		return s.toString();
	}
}
